import 'package:flutter/material.dart';
import 'package:qunaimedical/components/edit_text_field.dart';
import 'package:qunaimedical/components/primary_button.dart';
import 'package:qunaimedical/models/comment.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';

/// 回复评论界面
class CommentPage extends StatefulWidget {
  final Comment item;

  const CommentPage({Key key, this.item}) : super(key: key);

  @override
  _CommentPageState createState() => _CommentPageState();
}

class _CommentPageState extends State<CommentPage> {
  TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('回复评论'),
      ),
      body: ListView(
        children: [
          Container(
            child: Text('回复 @${widget.item.repliedName}'),
            padding: EdgeInsets.all(10),
          ),
          EditTextField(
            maxLines: 5,
            maxLength: 500,
            hintText: '发表回复',
            controller: _controller,
          ),
          PrimaryButton('回复', onPressed: _reply)
        ],
      ),
    );
  }

  void _reply() async {
    CommonUtils.hideKeyboard(context);
    String content = _controller.text.trim();
    if (content.isEmpty) {
      ToastUtil.show('内容不能为空', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.COMMENT_REPLY, {
      "commentId": widget.item.byRepliedId == null
          ? widget.item.id
          : widget.item.commentId, // 评论ID
      "byRepliedId": widget.item.repliedId, // 被回复人ID
      "repliedId": SPUtils.getUser().id, // 回复人ID
      "replyContent": content // 回复内容
    });
    Navigator.pop(context);
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 200) {
        Navigator.pop(context, true);
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
